package com.rolerealm.controller;

import com.rolerealm.common.result.Result;
import com.rolerealm.common.util.JwtUtil;
import com.rolerealm.common.util.ResultUtil;
import com.rolerealm.domain.dto.SpeechDTOs.SpeechRecognitionResponse;
import com.rolerealm.domain.dto.SpeechDTOs.SpeechSynthesisRequest;
import com.rolerealm.domain.dto.SpeechDTOs.SpeechSynthesisResponse;
import com.rolerealm.service.SpeechRecognitionService;
import com.rolerealm.service.SpeechSynthesisService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class SpeechController {

    private final JwtUtil jwtUtil;
    private final SpeechRecognitionService speechRecognitionService;
    private final SpeechSynthesisService speechSynthesisService;

    @PostMapping("/stt:recognize")
    public Result<SpeechRecognitionResponse> recognizeSpeech(
            @RequestHeader(name = "Authorization", required = false) String authorization,
            @RequestParam("file") MultipartFile file) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        String text = speechRecognitionService.recognize(file, userId);
        return ResultUtil.success(SpeechRecognitionResponse.builder().text(text).build());
    }

    @PostMapping("/tts:synthesize")
    public Result<SpeechSynthesisResponse> synthesizeSpeech(
            @RequestHeader(name = "Authorization", required = false) String authorization,
            @RequestBody @Valid SpeechSynthesisRequest request) {

        Long userId = jwtUtil.extractUserIdFromAuthorization(authorization);
        String url = speechSynthesisService.synthesize(request.getText(), request.getVoice(), request.getSpeed(), request.getPitch(), userId);
        return ResultUtil.success(SpeechSynthesisResponse.builder().audioUrl(url).build());
    }
}

@RestController
class FaviconController {

    @GetMapping(value = "/favicon.ico", produces = "image/x-icon")
    public ResponseEntity<byte[]> favicon() {
        return ResponseEntity.noContent().build();
    }
}


